﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using fmtx.Framework.NoSqlHelper;
using System.Net.Sockets;
using System.Net;

namespace SocketServer
{
    public class MongoService
    {
        MongoOperation<SocketBean> db = new MongoOperation<SocketBean>();

        /// <summary>
        /// 添加一个客户端
        /// </summary>
        /// <param name="bean"></param>
        public void Add(SocketBean bean)
        {
            db.Add(bean);
        }

        ///// <summary>
        ///// 更新或者添加
        ///// </summary>
        ///// <param name="bean"></param>
        //public void Save(SocketBean bean)
        //{
        //    var model = Get(bean.Cid);
        //    if (model != null)
        //    {
        //        Update(bean);
        //    }
        //    else {
        //        Add(bean);
        //    }
        //}

        /// <summary>
        /// 更新一个客户端信息
        /// </summary>
        /// <param name="bean"></param>
        public void Update(SocketBean bean)
        {
            db.Update(bean);
        }

        /// <summary>
        /// 获取一个客户端信息
        /// </summary>
        /// <param name="cid"></param>
        /// <returns></returns>
        public SocketBean Get(string cid)
        {
            return db.Get(w => w.Cid == cid);
        }

        /// <summary>
        /// 通过ip与端口查询客户端
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public SocketBean Get(string ipaddress, int port)
        {
            return db.Get(w => w.Ipaddress == ipaddress && w.Port == port);
        }

        /// <summary>
        /// 获取一个客户端信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public SocketBean GetByName(string name)
        {
            return db.Get(w => w.Name == name);
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <param name="cid"></param>
        public void LoginOut(string cid)
        {
            var bean = Get(cid);
            bean.IsOnline = false;
            Update(bean);
        }

        /// <summary>
        /// 获取客户端数
        /// </summary>
        /// <returns></returns>
        public long GetClientCount()
        {
           return db.Count(w=>w.IsOnline);
        }

        /// <summary>
        /// 获取所有客户端
        /// </summary>
        /// <returns></returns>
        public List<SocketBean> GetAll()
        {
            return db.AllList().ToList();
        }

        /// <summary>
        /// 移除所有数据
        /// </summary>
        public void RemoveAll()
        {
            var all = GetAll();
            foreach (var item in all)
            {
                LoginOut(item.Cid);
            }
        }
    }
}
